package com.security.demo.dao;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.security.demo.model.Role;
import com.security.demo.util.Pager;

@Repository
public class RoleDao extends SimpleJdbcDao<Role> {

	static String insertSql = "insert into t_role (id,name,description,available) values (:id,:name,:description,:available)";
	static String updateSql = "update t_role set name = :name,description = :description,available = :available where id = :id ";
	static String insertRoleResourceSql = "insert into t_role_resource (role_id,resource_id) values (?,?)";
	static String deleteRoleResourceSql = "delete from t_role_resource where role_id = ?";
	static String findResourceIdsSql = "select rr.resource_id from t_role_resource rr where rr.role_id = ?";

	public Pager<Role> findPager(int start, int limit, Object... args) {
		String sql = "select * from t_role ";
		if (ArrayUtils.isNotEmpty(args))
			sql += " where name like ? or description like ?";
		else
			args = NULL_PARA_ARRAY;
		return super.findPager(start, limit, sql, args);
	}

	public Boolean mergeRole(Role role) {
		return StringUtils.isBlank(role.getId()) ? saveRole(role) : updateRole(role);
	}

	public boolean saveRole(Role role) {
		String roleId = getId();
		role.setId(roleId);
		saveModel(insertSql, role);// save role
		List<String> resourceIds = role.getResourceIds();
		if (CollectionUtils.isNotEmpty(resourceIds)) { // save role-resource
			for (String resourceId : resourceIds) {
				jdbcTemplate.update(insertRoleResourceSql, new Object[] { roleId, resourceId });
			}
		}
		return true;
	}

	public boolean updateRole(Role role) {
		saveModel(updateSql, role); // update role
		List<String> resourceIds = role.getResourceIds();
		jdbcTemplate.update(deleteRoleResourceSql, new Object[] { role.getId() });
		if (CollectionUtils.isNotEmpty(resourceIds)) { // save role-resource
			for (String resourceId : resourceIds) {
				jdbcTemplate.update(insertRoleResourceSql, new Object[] { role.getId(), resourceId });
			}
		}
		return true;
	}

	
	public Set<String> findResourceIds(String roleId) {
		List<String> resourceIds = super.findStrings(findResourceIdsSql, roleId);
		return resourceIds != null && resourceIds.size() > 0 ? new HashSet<String>(resourceIds) : this.emptySet;
	}
}
